package com.psp.bu.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.northend.util.StringUtil;
import com.psp.bu.controller.res.bean.ROrderDetailBean;
import com.psp.bu.controller.res.bean.ROrderDetailCommentBean;
import com.psp.bu.controller.res.bean.ROrderDetailInvoiceAddressBean;
import com.psp.bu.controller.res.bean.ROrderDetailInvoiceHeaderBean;
import com.psp.bu.controller.res.bean.ROrderDetailProductBean;
import com.psp.bu.controller.res.bean.ROrderDetailReceiverBean;
import com.psp.bu.controller.res.bean.ROrderInvoiceAddressBean;
import com.psp.bu.controller.res.bean.ROrderInvoiceHeaderBean;
import com.psp.bu.controller.res.bean.ROrderListBean;
import com.psp.bu.controller.res.bean.ROrderListProductBean;
import com.psp.bu.controller.res.bean.ROrderReceiverBean;
import com.psp.bu.model.CommentBean;
import com.psp.bu.model.OrderBean;
import com.psp.bu.model.ProductAttributeBean;
import com.psp.bu.model.ProductBean;
import com.psp.bu.model.ProductSkuBean;
import com.psp.bu.model.UserBean;
import com.psp.bu.model.extend.InvoiceHeaderJson;
import com.psp.bu.model.extend.ReceiveAddressJson;
import com.psp.bu.persist.dao.AddressDao;
import com.psp.bu.persist.dao.CommentDao;
import com.psp.bu.persist.dao.InvoiceHeaderDao;
import com.psp.bu.persist.dao.OrderDao;
import com.psp.bu.persist.dao.ProductDao;
import com.psp.bu.persist.dao.UserDao;
import com.psp.bu.service.OrderService;
import com.psp.bu.service.exception.ServiceException;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	OrderDao orderImpl;

	@Autowired
	UserDao userImpl;
	
	@Autowired
	ProductDao productImpl;

	@Autowired
	AddressDao addressImpl;

	@Autowired
	InvoiceHeaderDao invoiceHeaderImpl;

	@Autowired
	CommentDao commentImpl;

	@Override
	public ROrderDetailBean getDetail(String buid, String oid) {
		ROrderDetailBean result = new ROrderDetailBean();
		if (StringUtil.isEmpty(buid)) {
			throw new ServiceException("object_is_not_exist", "用户");
		}
		OrderBean orderBean = orderImpl.selectByOid(oid);
		if (orderBean == null) {
			throw new ServiceException("object_is_not_exist", "订单");
		}

		String pid = orderBean.getPid();
		ProductBean product = productImpl.selectById(pid);
		List<CommentBean> commentList = commentImpl.selectByOid(oid);
		ProductSkuBean skuBean = productImpl.selectProductInfoBySukCode(orderBean.getSkuCode(), 0);
		List<ProductAttributeBean> pabList = productImpl.selectAttributeList(pid);

		String reAddress = orderBean.getReceiveAddress();
		String inHeader = orderBean.getInvoiceHeader();
		String inAddress = orderBean.getInvoiceAddress();

		result.setOid(oid);
		result.setPid(pid);
		result.setOrderNo(orderBean.getOrderNo());
		result.setCreateDate(orderBean.getCreateDate() != null ? orderBean.getCreateDate().getTime() : 0);
		result.setPrice(orderBean.getPrice());
		result.setTitle(orderBean.getTitle());
		result.setState(orderBean.getState());
		result.setFreight(orderBean.getFreight());
		result.setSpeed(orderBean.getSpeed());
		result.setUserName(orderBean.getUserName());
		result.setNum(orderBean.getNum());
		result.setInvoiceNo(orderBean.getInvoiceNo());
		ROrderDetailProductBean rp = null;
		ROrderDetailReceiverBean rr = new ROrderDetailReceiverBean();
		ROrderDetailInvoiceHeaderBean rh = new ROrderDetailInvoiceHeaderBean();
		ROrderDetailInvoiceAddressBean ria = new ROrderDetailInvoiceAddressBean();
		ROrderDetailCommentBean rc = new ROrderDetailCommentBean();

		if (product != null) {
			rp = new ROrderDetailProductBean();
			rp.setPcode(product.getPcode());
			rp.setPid(product.getPid());
			rp.setTitle(product.getTitle());
			rp.setSubTitle(product.getSubTitle());
			rp.setType(product.getType());
			rp.setImg(product.getImg());
			rp.setPrice(product.getPrice());
			rp.setQuoteType(product.getQuoteType());
			rp.setLinkMan(product.getLinkMan());
			rp.setTelephone(product.getTelephone());
			rp.setHasInvoice(product.getHasInvoice() == 1 ? true : false);
			rp.setMaterialInfo("");
			rp.setState(product.getState() == 1 ? true : false);
			JSONArray skuInfo = getSkuCodeInfo(skuBean, pabList);
			rp.setSkuInfo(skuInfo);
		}

		if (!StringUtil.isEmpty(reAddress)) {
			ReceiveAddressJson rec = JSON.parseObject(reAddress, ReceiveAddressJson.class);
			rr.setAddressee(rec.getName());
			rr.setPhone(rec.getPhone());
			rr.setProvince(rec.getProvince());
			rr.setCity(rec.getCity());
			rr.setDistrict(rec.getDistrict());
			rr.setDetail(rec.getDetail());
		}

		if (!StringUtil.isEmpty(inHeader)) {
			InvoiceHeaderJson ih = JSON.parseObject(inHeader, InvoiceHeaderJson.class);
			rh.setTitle(ih.getTitle());
			rh.setType(String.valueOf(ih.getType()));
		}

		if (!StringUtil.isEmpty(inAddress)) {
			ReceiveAddressJson rec = JSON.parseObject(inAddress, ReceiveAddressJson.class);
			ria.setAddressee(rec.getName());
			ria.setPhone(rec.getPhone());
			ria.setProvince(rec.getProvince());
			ria.setCity(rec.getCity());
			ria.setDistrict(rec.getDistrict());
			ria.setDetail(rec.getDetail());
		}

		if (commentList != null && commentList.size() > 0) {
			CommentBean comment = commentList.get(0);
			if (comment != null) {
				rc.setScores(comment.getScore());
				rc.setContent(comment.getContent());
			}
		}

		result.setProduct(rp);
		result.setReceiver(rr);
		result.setInvoiceHeader(rh);
		result.setInvoiceAddress(ria);
		result.setComment(rc);
		return result;
	}

	/**
	 * 
	 * @param skuBean
	 * @param pabList
	 * @return
	 */
	private JSONArray getSkuCodeInfo(ProductSkuBean skuBean, List<ProductAttributeBean> pabList) {
		JSONArray skuInfo = null;
		if (skuBean != null) {
			String skuJson = skuBean.getSkuJson();
			Set<Integer> acodes = null;
			Map<Integer, Integer> acodeMapValue = null;
			List<JSONObject> skuJsonArray = JSONArray.parseArray(skuJson, JSONObject.class);
			if (skuJsonArray != null && skuJsonArray.size() > 0) {
				acodes = new HashSet<>();
				acodeMapValue = new HashMap<>();
				for (int i = 0; i < skuJsonArray.size(); i++) {
					JSONObject ob = skuJsonArray.get(i);
					int acode = ob.getIntValue("acode");
					int value = ob.getIntValue("value");
					acodes.add(acode);
					acodeMapValue.put(acode, value);
				}
			}

			JSONArray attrs = new JSONArray();
			if (pabList != null && pabList.size() > 0) {
				Map<Integer, ProductAttributeBean> amap = pabList.stream()
						.collect(Collectors.toMap(ProductAttributeBean::getAcode, (p) -> p));
				if (acodes != null && acodes.size() > 0) {
					for (Integer acode : acodes) {
						Integer acodeValue = acodeMapValue.get(acode);
						ProductAttributeBean pab = amap.get(acode);
						if (pab == null)
							continue;
						String name = pab.getName();
						String subName = "";
						String valueJson = pab.getValue();
						List<JSONObject> valueJsonArray = JSONArray.parseArray(valueJson, JSONObject.class);
						if (valueJsonArray != null && valueJsonArray.size() > 0) {
							for (int i = 0; i < valueJsonArray.size(); i++) {
								JSONObject ob = valueJsonArray.get(i);
								int code = ob.getIntValue("code");
								String codeName = ob.getString("name");
								if (code == acodeValue) {
									subName = codeName;
									break;
								}
							}
						}

						JSONObject aa = new JSONObject();
						aa.put("label", name);
						aa.put("value", subName);
						attrs.add(aa);
					}
				}
			}
			skuInfo = attrs;
		}
		return skuInfo;
	}

	@Override
	public PageResult<ROrderListBean> getList(int page, int pageSize, String buid, String orderNo, Integer state) {
		PageResult<ROrderListBean> result = new PageResult<ROrderListBean>();
		UserBean user = userImpl.selectOne(buid);
		if(user.getCateCode() == 99) {
			buid = null;// 查询所有分类
		}
		int[] s = {state};
		if(state == 0) {
			s = null;
		}
		if(state == 1) {
			s = new int[]{1,2};
		}
		int count = orderImpl.selectCount(buid, orderNo, s);
		// TODO 根据订单 state 状态 查询
		List<OrderBean> reslist = orderImpl.selectList(page, pageSize, buid, orderNo, s);

		Set<String> pids = new HashSet<>();
		List<ProductBean> productList = null;
		if (reslist != null && reslist.size() > 0) {
			for (OrderBean bean : reslist) {
				pids.add(StringUtil.isEmpty(bean.getPid()) ? null : bean.getPid());
			}
			productList = productImpl.selectByPids(pids);
		}
		Map<String, ProductBean> mapProduct = new HashMap<>();
		if (productList != null && productList.size() > 0) {
			mapProduct = productList.stream().collect(Collectors.toMap(ProductBean::getPid, (p) -> p));
		}
		List<ROrderListBean> list = new ArrayList<>();
		if (reslist != null && reslist.size() > 0) {
			for (OrderBean bean : reslist) {
				ROrderListBean rb = new ROrderListBean();

				rb.setOid(bean.getOid());
				rb.setOrderNo(bean.getOrderNo());
				rb.setCreateDate(bean.getCreateDate() != null ? bean.getCreateDate().getTime() : 0);
				rb.setPrice(bean.getTotalPrice());
				rb.setTitle(bean.getTitle());
				rb.setState(bean.getState());
				rb.setSkuCode(bean.getSkuCode());
				rb.setNum(bean.getNum());
				rb.setUserName(bean.getUserName());
				rb.setInvoiceNo(bean.getInvoiceNo());
				ProductBean product = mapProduct.get(bean.getPid());
				ROrderListProductBean rop = new ROrderListProductBean();
				if (product != null) {
					rop.setPcode(String.valueOf(product.getPcode()));
					rop.setPid(product.getPid());
					rop.setTitle(product.getTitle());
					rop.setImg(product.getImg());
					rop.setType(product.getType());
					rop.setPrice(product.getPrice());
					rop.setQuoteType(product.getQuoteType());
					rop.setLinkMan(product.getLinkMan());
					rop.setTelephone(product.getTelephone());
				}
				String reAddress = bean.getReceiveAddress();
				String inHeader = bean.getInvoiceHeader();
				String inAddress = bean.getInvoiceAddress();

				ROrderReceiverBean ror = new ROrderReceiverBean();
				if (!StringUtil.isEmpty(reAddress)) {
					ReceiveAddressJson rec = JSON.parseObject(reAddress, ReceiveAddressJson.class);
					ror.setAddressee(rec.getName());
					ror.setPhone(rec.getPhone());
					ror.setProvince(rec.getProvince());
					ror.setCity(rec.getCity());
					ror.setDistrict(rec.getDistrict());
					ror.setDetail(rec.getDetail());
				}

				ROrderInvoiceHeaderBean roi = new ROrderInvoiceHeaderBean();
				if (!StringUtil.isEmpty(inHeader)) {
					InvoiceHeaderJson ih = JSON.parseObject(inHeader, InvoiceHeaderJson.class);
					roi.setTitle(ih.getTitle());
					roi.setType(String.valueOf(ih.getType()));
				}

				ROrderInvoiceAddressBean roa = new ROrderInvoiceAddressBean();
				if (!StringUtil.isEmpty(inAddress)) {
					ReceiveAddressJson rec = JSON.parseObject(inAddress, ReceiveAddressJson.class);
					roa.setAddressee(rec.getName());
					roa.setPhone(rec.getPhone());
					roa.setProvince(rec.getProvince());
					roa.setCity(rec.getCity());
					roa.setDistrict(rec.getDistrict());
					roa.setDetail(rec.getDetail());
				}

				rb.setProduct(rop);
				rb.setReceiver(ror);
				rb.setInvoiceAddress(roa);
				rb.setInvoiceHeader(roi);
				list.add(rb);
			}
		}

		result.setCount(count);
		result.setData(list);
		return result;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean dispatch(String uid, String oid, String spid) throws ServiceException {
		// boolean flag = false;
		return true;
	}

}
